/**
 * @project sky-take-out_1
 * @author MECHREVO
 * @date 2023/12/9 10:38:43
 * @version 1.0
 */
package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.Category;
import com.sky.entity.Setmeal;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.Userservice;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.DishItemVO;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl implements Userservice {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public UserLoginVO login(String code) {
        String openid = getOpenid(code);
        User userQuery = new User();
        userQuery.setOpenid(openid);
        User user = userMapper.selectOne(userQuery);
        if (Objects.isNull(user)) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        Map<String, Object> claims=new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims
        );
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setOpenid(openid);
        userLoginVO.setId(user.getId());
        userLoginVO.setToken(token);
        return userLoginVO;
    }

    @Override
    @Cacheable(value = "SETMEAL", key = "#categoryId")
    public List<Setmeal> selectsetmeal(Long categoryId) {
        List<Setmeal> setmeal=userMapper.selectsetmeal(categoryId);
        return setmeal;
    }

    @Override
    public List<DishItemVO> selectsetmealdish(Long id) {
        return userMapper.selectsetmealdish(id);
    }


    private String getOpenid(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("appid", "wx11829d976b754543");
        map.put("secret", "299d78446be88a07cb4d2c551056870b");
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        log.info("从微信回来的数据：{}", json);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
